// pages/blue/index.js
const app = getApp();
const ems_name_prefix = app.globalData.ems_name_prefix;
const ems_all_name_prefix = app.globalData.ems_all_name_prefix;
const ems_name_blte_prefix = app.globalData.ems_name_blte_prefix;
let initBlueTime;
let isVisable = true;
let isVisableAuthor = false;
const RUN_EMS = "12";
const BLET_EMS = "14";
const BLET_ONE_EMS = "20";
const ALL_EMS = "19";
Page({
  data: {
    status: "",
    sousuo: "",
    connectedDeviceId: "", //已连接设备uuid
    services: [], // 连接设备的服务
    serviceId: "",
    connected: false,
    chs: [],
    canWrite: false,
    characteristics: "", // 连接设备的状态值
    writeServicweId: "", // 可写服务uuid
    writeCharacteristicsId: "", //可写特征值uuid
    readServicweId: "", // 可读服务uuid
    readCharacteristicsId: "", //可读特征值uuid
    notifyServicweId: "", //通知服务UUid
    notifyCharacteristicsId: "", //通知特征值UUID
    inputValue: "",
    defaultBlue: "", //默认设备
    isFirestShow: true,
    isBloothOpen: false,
    isAllowLocation: false,
    isCloseByHandle: false, //是否手动断开
    scanCount: 0
  },
  onLoad: function (options) {
    if (options && options.isAutoConnect) {
      app.globalData.isAutoConnect = options.isAutoConnect;
    }
    this.getDefaultBlue();
    this.checkAppSupport();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    isVisable = true;
    var that = this;
    this.setData({
      connectedDeviceId: app.globalData.connectedDeviceId
    });
    if (app.getPlatform() == "android") {
      that.checkAndroidDeviceGpsAndLocation(that.initBlue);
    } else {
      that.checkIOSDeviceGpsAndLocation(that.initBlue);
    }
  },
  // 初始化蓝牙适配器
  initializeBluetooth: function () {
    var that = this;
    if (app.getPlatform() == "android") {
      if (!that.data.isAllowLocation) {
        that.onShow();
        return;
      }
    }
    if (this.data.devices.length == 0 && app.globalData.connectedDeviceId.length < 1) {
      console.log("init blue 扫描");
      if (!this.data.isBloothOpen) {
        // this.showOpenblueDialog();
        return;
      }
      wx.showLoading("扫描中...");
      wx.closeBluetoothAdapter({
        success: function (res) {
          console.log("close blue success");
          wx.openBluetoothAdapter({
            success: function (res) {
              console.log("open blue success");
              setTimeout(function () {
                wx.hideLoading();
                that.searchBluetooth();
              }, 2000);
            }
          });
        }
      });
    } else {
      if (!this.data.isBloothOpen) {
        this.showOpenblueDialog();
      } else {
        this.searchBluetooth();
      }
    }
  },

  //搜索获取已发现设备
  searchBluetooth: function () {
    wx.showLoading("扫描中...");
    var that = this;
    that.setData({
      devices: []
    });
    that.data.scanCount++;
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      //开始搜寻附近的蓝牙外围设备
      success: function (res) {
        console.log("开始搜索周边蓝牙设备");
        console.log(res);
        wx.getBluetoothDevices({
          //sucess返回uuid 对应的的已连接设备列表，Array类型
          success: function (res) {
            let isScanDevice = false;
            console.log("扫描到的设备:" + JSON.stringify(res));
            if (res.length > 10) {
              isScanDevice = true;
            }
            //是否有已连接设备
            wx.getConnectedBluetoothDevices({
              ////根据 uuid 获取处于已连接状态的设备
              success: function (res) {
                console.log("已连接的蓝牙设备:" + JSON.stringify(res.devices));
                if (res.devices.length > 0) {
                  isScanDevice = true;
                } else {
                  that.setData({
                    connected: false,
                    chs: [],
                    canWrite: false
                  });
                }
              }
            });
            let foundDevice = res.devices;
            wx.onBluetoothDeviceFound(function (devices) {
              console.log("新的的蓝牙设备:" + JSON.stringify(devices));
              var isnotExist = true
              if (devices.deviceId) {
                for (var i = 0; i < foundDevice.length; i++) {
                  if (devices.deviceId == foundDevice[i].deviceId) {
                    isnotExist = false
                  }
                }
                if (isnotExist)
                  foundDevice.push(devices)
              }
              else if (devices.devices) {
                for (var i = 0; i < foundDevice.length; i++) {
                  if (devices.devices[0].deviceId == foundDevice[i].deviceId) {
                    isnotExist = false
                  }
                }
                if (isnotExist)
                  foundDevice.push(devices.devices[0])
              }
              else if (devices[0]) {
                for (var i = 0; i < foundDevice.length; i++) {
                  if (devices[0].deviceId == foundDevice[i].deviceId) {
                    isnotExist = false
                  }
                }
                if (isnotExist)
                  foundDevice.push(devices[0])
              }
              console.log("checkAbcEms1")
              let checkedDevice = that.checkAbcEms(foundDevice);
              that.setData({
                devices: checkedDevice
              });
            })
            console.log("checkAbcEms2")
            let checkedDevice = that.checkAbcEms(foundDevice);
            that.setData({
              devices: checkedDevice
            });
            var scan_time_out = 2000;
            if (app.getPlatform() == "android") {
              scan_time_out = 4000;
            }
            setTimeout(function () {
              wx.hideLoading();
              console.log("5s未扫描到")
              if (foundDevice.length == 0 && that.data.scanCount < 3) {
                wx.stopBluetoothDevicesDiscovery({
                  success: function (res) {
                    console.log("5s未扫描到 停止搜索周边设备1:");
                  }
                });
                that.initializeBluetooth();
              }
            }, scan_time_out);
          }
        });
      }
    });
  },

  initBlue() {
    var that = this;
    wx.showLoading("初始化中...");
    that.setData({
      isAllowLocation: true
    });
    wx.openBluetoothAdapter({
      //调用微信小程序api 打开蓝牙适配器接口
      success: function (res) {
        that.getTheBlueDisConnectWithAccident(); //监听蓝牙是否会异常断开
        setTimeout(function () {
          wx.hideLoading();
          that.searchBluetooth();
        }, 500);
        that.setData({
          isBloothOpen: true
        });
        that.monitorTheBlue();
      },

      fail: function (res) {
        //如果手机上的蓝牙没有打开，可以提醒用户
        if (that.data.isFirestShow) {
          that.showOpenblueDialog();
        }
        that.clearConnectedDevice();
        that.setData({
          isBloothOpen: false,
          isFirestShow: false
        });
        console.log(res);
        console.log("蓝牙为关闭");
        initBlueTime = setTimeout(function () {
          if (isVisable) {
            that.initBlue();
          }
        }, 1000);
      }
    });
  },
  //监听手机蓝牙开关 判定手机蓝牙是否打开判定手机蓝牙是否打开
  //监听手机蓝牙的开关
  monitorTheBlue: function () {
    var that = this;
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log(`adapterState changed, now is`, res);
      if (res.available) {
        that.setData({
          isBloothOpen: true,
          connectionEquipment: "请打开设备，并靠近手机"
        });
      } else {
        that.clearConnectedDevice();
        that.setData({
          isBloothOpen: false,
          isFirestShow: false
        });
        that.showOpenblueDialog();
      }
    });
  },
  //监听蓝牙设备是否会异常断开
  getTheBlueDisConnectWithAccident: function () {
    var that = this;
    wx.onBLEConnectionStateChange(function (res) {
      console.log("监听:" + JSON.stringify(res));
      if (!res.connected) {
        that.clearConnectedDevice();
        if (that.data.isCloseByHandle) {
          that.clearConnectedDevice();
          that.setData({
            isCloseByHandle: false
          });
        } else {
          that.showDisconnectDialog();
        }
        wx.closeBluetoothAdapter({
          success: function (res) {
            wx.openBluetoothAdapter({
              success: function (res) { }
            });
          }
        });
      }
    });
  },
  //连接设备
  connectTO: function (e) {
    var that = this;
    let toConnectedDeviceId = e.currentTarget.id;
    var deviceName = e.currentTarget.dataset.name;
    app.globalData.isAutoConnect = 1;
    let fdStart = deviceName.indexOf(ems_name_prefix);
    let allEmsStart = deviceName.indexOf(ems_all_name_prefix);
    let oneBletStart = deviceName.indexOf(ems_name_blte_prefix);
    if (fdStart == 0 || allEmsStart == 0 || oneBletStart == 0) {
      wx.setStorage({
        key: "emsDeviceCode",
        data: deviceName
      });
      that.connectEmsAction(toConnectedDeviceId, deviceName);
    } else {
      wx.showToast({
        title: "不支持该设备",
        icon: "none",
        image: "",
        duration: 1500,
        mask: false,
        success: result => { },
        fail: () => { },
        complete: () => { }
      });
      return;
    }
  },

  //实际连接操作
  connectEmsAction: function (toConnectedDeviceId, deviceName) {
    var that = this;
    if (
      this.data.connectedDeviceId != "" &&
      this.data.connectedDeviceId != toConnectedDeviceId
    ) {
      wx.showToast({
        title: "已有设备连接,请断开后再连",
        icon: "none",
        image: "",
        duration: 1500,
        mask: false,
        success: result => { },
        fail: () => { },
        complete: () => { }
      });
      return;
    }
    wx.stopBluetoothDevicesDiscovery({
      //先停止搜索周边设备
      success: function (res) {
        console.log("连接设备前，先停止搜索周边设备:");
        console.log(res);
      }
    });
    if (this.data.connectedDeviceId == toConnectedDeviceId) {
      console.log("connectSuccess 222222")
      that.connectSuccess(toConnectedDeviceId, deviceName);
      return;
    }
    wx.showLoading({
      title: "连接蓝牙设备中...",
      mask: true
    });
    wx.createBLEConnection({
      //若小程序在之前已有搜索过某个蓝牙设备，并成功建立链接，可直接传入之前搜索获取的deviceId直接尝试连接该设备，无需进行搜索操作。
      deviceId: toConnectedDeviceId,
      timeout: 5000,
      success: function (res) {
        console.log("连接成功:");
        console.log(res);
        console.log("connectSuccess 333333")
        that.connectSuccess(toConnectedDeviceId, deviceName);
        that.saveDefaulBlue(toConnectedDeviceId);
      },
      fail: function () {
        wx.hideLoading();
        console.log("调用失败");
        that.data.devices = [];
        that.initializeBluetooth();
      },
      complete: function () {
        console.log("已连接设备ID：" + toConnectedDeviceId);
        console.log("调用结束");
      }
    });
  },

  //连接成功的结果
  connectSuccess: function (toConnectedDeviceId, deviceName) {
    var that = this;
    wx.hideLoading();
    that.setData({
      connectedDeviceId: toConnectedDeviceId, //currentTarget: 事件绑定的元素
      msg: "已连接" + toConnectedDeviceId,
      isFirestShow:true
    });
    app.globalData.connectedDeviceId = toConnectedDeviceId;
    that.saveDefaulBlue(toConnectedDeviceId);
    setTimeout(() => {
      let url = "/pages/GPM32/index?deviceId=";
      this.jumpToEmsView('jdy', url, deviceName);
    }, 500);
    wx.hideLoading();
  },
  //控制界面
  jumpToControl: function (deviceName) {
    var deviceViewUrl;
    if (app.globalData.isAutoConnect == 0) {
      //非自动连接
      return;
    }
    app.globalData.isAutoConnect = 0;
    if (!deviceName) {
      return;
    }
    let fdStart = deviceName.indexOf(ems_name_prefix);
    let emsOneBlet = deviceName.indexOf(ems_name_blte_prefix);
    var devType;
    if (fdStart == 0) {
      // if (deviceName==this.data.defaultBlue) {
        //已有设备连接过
        let deviceConnectType ="18";
        if (app.checkDevType(deviceConnectType)) {
          let url = "/pages/ems-part/index?deviceId=";
          this.jumpToEmsView(deviceConnectType, url, deviceName);
          return;
        }
      // }
      devType=RUN_EMS;
      // deviceViewUrl = "/pages/device-select/index?deviceId=";
    } else if (emsOneBlet == 0) {
      devType = BLET_ONE_EMS;
      if (deviceName == this.data.defaultBlue) {
        //已有设备连接过
        let deviceConnectType = this.getDeviceConnectType(deviceName);
        if (deviceConnectType && app.checkDevType(deviceConnectType)) {
          let url = "/pages/GPM32/index?deviceId=";
          this.jumpToEmsView(deviceConnectType, url, deviceName);
          return;
        }
      }
      deviceViewUrl = "/pages/train-model/index?deviceId=";
    } else {
      devType = ALL_EMS;
      deviceViewUrl = "/pages/blueControls/index?deviceId=";
    }
    wx.navigateTo({
      url: deviceViewUrl + this.data.connectedDeviceId + "&devType=" + devType + "&deviceName=" + deviceName,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { }
    });
  },
  //直接跳转界面 部位训练
  jumpToEmsView: function (_devType, url, deviceName) {
    var devType = _devType;
    let deviceViewUrl = url+ this.data.connectedDeviceId + "&devType=" + devType + "&deviceName=" + deviceName;
    wx.navigateTo({
      url: deviceViewUrl ,
      success: function (res) { },
      fail: function (res) { 
        console.log(res)
      },
      complete: function (res) { 
        console.log(res)
      }
    });
  },
  // 获取连接设备的service服务
  getServices: function () {
    var that = this;
    wx.getBLEDeviceServices({
      //获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备，包括已经和本机处于连接状态的设备
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        //console.log('获取蓝牙设备所有服务成功：', res);
        that.data.services = res.services;
        console.log("获取蓝牙设备所有服务成功：", that.data.services);
        that.setData({
          serviceId: that.data.services[0].uuid
        });
        console.log("服务uuid:", that.data.serviceId);
        wx.getBLEDeviceCharacteristics({
          // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
          deviceId: that.data.connectedDeviceId,
          // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
          serviceId: that.data.serviceId, //-----注意是that.data.services[0].uuid
          success: function (res) {
            console.log(
              "serviceId: that.data.services[0].uuid: ",
              that.data.serviceId
            );
            console.log(res);
            for (var i = 0; i < res.characteristics.length; i++) {
              if (res.characteristics[i].properties.notify) {
                //注意characteristic(特征值)信息,properties对象
                that.setData({
                  notifyServicweId: that.data.services[0].uuid,
                  notifyCharacteristicsId: res.characteristics[i].uuid
                });
                console.log(
                  "notifyServicweId:",
                  that.data.notifyServicweId,
                  "notifyCharacteristicsId",
                  that.data.notifyCharacteristicsId
                );
              }
              if (res.characteristics[i].properties.write) {
                that.setData({
                  writeServicweId: that.data.services[0].uuid,
                  writeCharacteristicsId: res.characteristics[i].uuid
                });
                console.log(
                  "writeServicweId:",
                  that.data.writeServicweId,
                  "writeCharacteristicsId",
                  that.data.writeCharacteristicsId
                );
              } else if (res.characteristics[i].properties.read) {
                that.setData({
                  readServicweId: that.data.services[0].uuid,
                  readCharacteristicsId: res.characteristics[i].uuid
                });
                console.log(
                  "readServicweId:",
                  that.data.readServicweId,
                  "readCharacteristicsId",
                  that.data.readCharacteristicsId
                );
              }
            }
          },
          fail: function () {
            console.log("获取连接设备的所有特征值：", res);
          },
          complete: function () {
            console.log("complete!");
          }
        });
      }
    });
  },

  //断开设备连接
  closeBluetooth: function (e) {
    var that = this;
    wx.showLoading({
      title: "设备断开中.."
    });
    app.globalData.isAutoConnect = 0;
    that.setData({
      isCloseByHandle: true
    });
    wx.closeBLEConnection({
      deviceId: e.currentTarget.id,
      success: function (res) {
        that.clearConnectedDevice();
        that.setData({
          connected: false,
          chs: [],
          canWrite: false,
          connectedDeviceId: "",
          isCloseByHandle: true
        });
        wx.hideLoading();
        console.log("断开设备连接: ", e.currentTarget.id);
        console.log(res);
      },
      fail: function (es) {
        that.clearConnectedDevice();
        that.setData({
          connected: false,
          chs: [],
          canWrite: false,
          connectedDeviceId: ""
        });
        if (es == 10001) {
          that.showOpenblueDialog();
        }
        wx.hideLoading();
      }
    });
  },
  //清除连接的设备
  clearConnectedDevice: function () {
    app.globalData.connectedDeviceId = "";
  },
  //发送
  sendMessages: function () {
    var that = this;
    // 这里的回调可以获取到 write 导致的特征值改变
    wx.onBLECharacteristicValueChange(function (characteristic) {
      console.log("characteristic value changed:1", characteristic);
    });
    var buf = new ArrayBuffer(16);
    var dataView = new DataView(buf);
    dataView.setUint8(0, 99);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.writeServicweId,
      characteristicId: that.data.writeCharacteristicsId,
      value: buf,
      success: function (res) {
        console.log("writeBLECharacteristicValue success", res);
      }
    });
  },

  //启用低功耗蓝牙设备特征值变化时的 notify 功能
  startBletNotify: function () {
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.notifyServicweId,
      characteristicId: that.data.notifyCharacteristicsId,
      success: function (res) {
        console.log("notifyBLECharacteristicValueChange success", res.errMsg);
      },
      fail: function () {
        console.log("启用notify功能失败！");
        console.log(that.data.notifyServicweId);
        console.log(that.data.notifyCharacteristicsId);
      }
    });
  },

  //接收消息
  receiveMessages: function () {
    var that = this;
    // 必须在这里的回调才能获取
    wx.onBLECharacteristicValueChange(function (characteristic) {
      let hex = Array.prototype.map
        .call(new Uint8Array(characteristic.value), x =>
          ("00" + x.toString(16)).slice(-2)
        )
        .join("");
      console.log(hex);
    });
    console.log(that.data.readServicweId);
    console.log(that.data.readCharacteristicsId);
    wx.readBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.readServicweId,
      characteristicId: that.data.readCharacteristicsId,
      success: function (res) {
        console.log("readBLECharacteristicValue:", res.errMsg);
      }
    });
  },

  onHide: function () {
    isVisable = false;
    var that = this;
    this.setData({
      devices: []
    });
    wx.stopBluetoothDevicesDiscovery({
      //隐藏界面是建议停止
      success: function (res) {
        console.log(res);
        that.setData({
          searching: false
        });
      }
    });
  },

  //全身训练
  goEmsAll: function () {
    wx.navigateTo({
      url: "/pages/ems-part/index"
    });
  },
  //切换默认设置
  switchDefault: function (e) {
    if (e.type != "change") {
      return;
    }
    if (e.detail.value) {
      this.saveDefaulBlue(e.currentTarget.id);
    } else {
      this.saveDefaulBlue("");
    }
  },
  //get default device
  getDefaultBlue: function () {
    var that = this;
    wx.getStorage({
      key: "defaultBlue",
      success: result => {
        that.setData({
          defaultBlue: result.data
        });
      },
      fail: () => { },
      complete: () => { }
    });
  },
  //save default device
  saveDefaulBlue: function (blueMac) {
    this.setData({
      defaultBlue: blueMac
    });
    wx.setStorage({
      key: "defaultBlue",
      data: blueMac,
      success: result => { },
      fail: () => { },
      complete: () => { }
    });
  },
  //校验ABC ems
  checkAbcEms: function (devices) {
    if (!devices) return;
    let sortDevice = [];
    for (let i = 0; i < devices.length; i++) {
      if (!devices[i].localName) {
        devices[i].localName = devices[i].name;
      }
      if (!devices[i].name) {
        devices[i].name = devices[i].localName;
      }
      if (!devices[i].name || !devices[i].localName) {
        continue;
      }
      if (app.checkConnectAuthor(devices[i])) {
        if (devices[i].localName && devices[i].name != devices[i].localName) {
          devices[i].name = devices[i].localName;
        }
        if (devices[i].name.startsWith(app.globalData.part_one_blet_type)) {
          // let name =
          //   ems_name_blte_prefix +
          //   devices[i].name.substring(
          //     devices[i].name.length - 6,
          //     devices[i].name.length
          //   ) + ")";
          // devices[i].name = name;
          devices[i].isAbc = true;
        }

        if (!this.checkDeivceExist(sortDevice, devices[i].deviceId)) {
          sortDevice.unshift(devices[i]);
        } else {
          if (!this.checkDeivceExist(sortDevice, devices[i].deviceId)) {
            sortDevice.push(devices[i]);
          }
        }
        if (devices[i].deviceId == this.data.defaultBlue) {
          // if (app.globalData.isAutoConnect == 1 && !devices[i].localName.startsWith(app.globalData.part_all_type)) {
          //   console.log("connect ems Action")
          //   this.connectEmsAction(devices[i].deviceId, devices[i].name);
          // }
        }
      }
    }
    return sortDevice;
  },

  //排除重复数据
  checkDeivceExist: function (devicesArr, deviceId) {
    let isExist = false;
    if (devicesArr.length == 0) {
      isExist = false;
    }
    for (let i = 0; i < devicesArr.length; i++) {
      if (devicesArr[i].deviceId == deviceId) {
        isExist = true;
        break;
      }
    }
    return isExist;
  },

  versionCompare: function (ver1, ver2) {
    //版本比较
    var version1pre = parseFloat(ver1);
    var version2pre = parseFloat(ver2);
    var version1next = parseInt(ver1.replace(version1pre + ".", ""));
    var version2next = parseInt(ver2.replace(version2pre + ".", ""));
    if (version1pre > version2pre) return true;
    else if (version1pre < version2pre) return false;
    else {
      if (version1next > version2next) return true;
      else return false;
    }
  },
  //微信版本检查
  checkAppSupport: function () {
    if (
      app.getPlatform() == "android" &&
      this.versionCompare("6.5.7", app.getVersion())
    ) {
      wx.showModal({
        title: "提示",
        content: "当前微信版本过低，请更新至最新版本",
        showCancel: false
      });
    } else if (
      app.getPlatform() == "ios" &&
      this.versionCompare("6.5.6", app.getVersion())
    ) {
      wx.showModal({
        title: "提示",
        content: "当前微信版本过低，请更新至最新版本",
        showCancel: false
      });
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("devic manage onUnload");
    // if (this.data.devices.length == 0) {
    //   wx.closeBluetoothAdapter({
    //     success: function (res) {
    //       wx.openBluetoothAdapter({
    //         success: function (res) {
    //           console.log("open blue success");
    //         }
    //       });
    //     }
    //   });
    // }

  },
  //连接断开提示
  showDisconnectDialog: function () {
    let that = this;
    if (!isVisable) return;
    if(!that.data.isFirestShow) return;
    this.setData({
      isFirestShow: false,
      connectedDeviceId: ""
    });
    wx.showModal({
      title: "提示",
      content: "微型智盒,连接已断开",
      showCancel: true,
      cancelText: '取消',
      cancelColor: "#000000",
      confirmText: "重新连接",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {
        if (result.confirm) {
          that.connectEmsAction();
        }
      },
      fail: () => {

      },
      complete: () => { }
    });
  },
  //打开蓝牙设备
  showOpenblueDialog: function () {
    if (!isVisable) return;
    let that = this;
    wx.showModal({
      title: "提示",
      content: "请打开手机蓝牙,并授权微信访问蓝牙",
      showCancel: false,
      cancelText: "",
      cancelColor: "#000000",
      confirmText: "确定",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {
        if (result.confirm) {
          wx.navigateBack({
            delta: 1,
          })
        }
      },
      fail: () => { },
      complete: () => { }
    });
  },
  testJumpOneBlet: function () {
    var deviceViewUrl = "/pages/ems_one_blet/index";
    wx.navigateTo({
      url: deviceViewUrl,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { }
    });
  },
  //位置授权
  onAuthLocation() {
    var that = this;
    wx.authorize({
      scope: 'scope.userLocation',
      success: (res) => {
        console.log('微信授权了：', res)
        that.getLocation();//获取位置
      },
      fail: (res) => {
        that.showOpenLocation();
        console.log('微信授未权了', res)
      },
    })
  },
  //获取授权提示
  getLocation: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84', //表示使用GPS定位
      success: (res) => {
        console.log("定位成功 = ", res)
        that.initBlue();
      },
      //表示用户没有开启授权  "getLocation:fail:system permission denied"
      fail: (res) => {
        console.log(this.data)
        if (res.errMsg) {
          let str = "system permission denied";
          if (res.errMsg.indexOf(str) != -1) {
            that.showAuthorLocationDialog();
            return;
          }
        }
        wx.getSetting({
          success: (res) => {
            if (!res.authSetting["scope.userLocation"]) {
              that.showAuthorLocationDialog();
            } else {
              //用户已经授权了，未打开gps 提示用户操作
              that.showOpenGpsDailog();
            }
          },
          fail: () => { },
          complete: () => { }
        });
      }
    })
  },
  //跳转到位置授权界面
  showOpenLocation: function () {
    var that = this;
    wx.showModal({
      title: "提示",
      content: "扫描蓝牙设备,需要您授权位置服务",
      showCancel: false,
      cancelText: '取消',
      cancelColor: "#000000",
      confirmText: "打开授权",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {
        if (result.confirm) {
          that.gotoSetting();
          // wx.navigateTo({
          //   url: "/pages/location/index",
          //   success: function (res) { },
          //   fail: function (res) { },
          //   complete: function (res) { },
          // })
        } else if (result.cancel) {

        }
      },
      fail: () => {

      },
      complete: () => { }
    });
  },
  //授权面板
  gotoSetting() {
    wx.openSetting({
      success: (res) => {
        console.log(res);
      }
    })
  },
  //获取位置服务提醒
  showAuthorLocationDialog() {
    if (isVisableAuthor) {
      return;
    }
    isVisableAuthor = true;
    wx.showModal({
      title: '提示',
      showCancel: false,
      content: '使用蓝牙设备,需要您在手机 设置->应用管理->微信->权限->打开您的位置开关。打开后,请点击扫描按钮',
      confirmText: "确认",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {
        isVisableAuthor = false;
      }
    })
  },
  //提示打开gps
  showOpenGpsDailog() {
    wx.showModal({
      title: '',
      showCancel: false,
      content: '请在系统设置中,打开GPS定位服务,打开后,请点击扫描按钮',
      confirmText: "确认",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {

      }
    })
  },
  //获取默认连接的设备
  getDeviceConnectType:function(deviceName){
    return wx.getStorageSync(deviceName + "_defaultType");
  },
  /**
   * 判断gps或者蓝牙是否打开
   * @param {回调方法} callback 
   */
  checkAndroidDeviceGpsAndLocation:function(callback){
    wx.getSystemInfo({
      success: function (res) {
        var res = wx.getSystemInfoSync();
        if (!res.bluetoothEnabled && !res.locationEnabled) {
          wx.showModal({
            title: '提示',
            content: '您的蓝牙和GPS未开启,请先开启蓝牙和GPS',
            showCancel: false,
            success: function () {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        } else if (!res.bluetoothEnabled) {
          wx.showModal({
            title: '提示',
            content: '您的蓝牙未开启,请先开启蓝牙',
            showCancel: false,
            success: function () {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        } else if (!res.locationEnabled) {
          wx.showModal({
            title: '提示',
            content: '您的GPS未开启,请先开启GPS',
            showCancel: false,
            success: function () {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        } else if (res.bluetoothEnabled && res.locationEnabled) {
          if (callback) {// 这里是回调方法
            callback() // 这里是回调方法
          }
        }
      },
    })
  },
  checkIOSDeviceGpsAndLocation:function(callback){
    wx.getSystemInfo({
      success: function (res) {
        var res = wx.getSystemInfoSync();
       if (!res.bluetoothEnabled) {
          wx.showModal({
            title: '提示',
            content: '您的蓝牙未开启,请先开启蓝牙',
            showCancel: false,
            success: function () {
             
            }
          })
        } else if (res.bluetoothEnabled) {
          if (callback) {
            callback()
          }
        }
      },
    })

  }
});
